package Controller;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Session;
import org.zkoss.zk.ui.Sessions;

import databaseHelper.UserDAO;


/**
 * a class to coordinate the login process
 * 
 * @author Rupert
 *
 */
public class UserCredentialManager {

	/**
	 * Name of the attribute to manage the user in the session
	 */
	public static final String KEY_USER_Model = "UserCredentialManager_MODEL";
	
	private UserDAO userDAO;
	
	private int userId = -1;
	
	private UserCredentialManager(){
		userDAO = new UserDAO();
	}
	
	
	public UserCredentialManager(String userName){
		userDAO = new UserDAO();
		userId = userDAO.getId(userName);
		System.out.println("New UserID :" +userId);
	}
	
	public static UserCredentialManager getInstance(){
		return getInstance(Sessions.getCurrent());
	}
	
	public static UserCredentialManager getInstance(Session zkSession){
		
		UserCredentialManager usermodel = (UserCredentialManager) zkSession.getAttribute(KEY_USER_Model);
		if(usermodel == null){
			zkSession.setAttribute(KEY_USER_Model, usermodel = new UserCredentialManager());
		}
		return usermodel;
		
	}
	public boolean isAuthenticated(){
		if(userId >= 0){
			return true;
		}
		return false;
	}
	
	/**
	 * remove login attribute and return to login page
	 */
	public static void doLogout(){
		Sessions.getCurrent().removeAttribute(KEY_USER_Model);
		Executions.sendRedirect("login.zul");
	}
	
	/**
	 * get User id of logged in user
	 * 
	 * @return
	 */
	public int getUserId(){
		return userId;
	}
	
	
}
